﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Threading;
using AnjLab.SyncIT.App;
using AnjLab.SyncIT.App.Properties;
using AnjLab.SyncIT.Core;
using AnjLab.SyncIT.Core.Api;
using IWshRuntimeLibrary;
using Application=System.Windows.Application;
using Res = AnjLab.SyncIT.App.Properties.Resources;

namespace AnjLab.SyncIT.App
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private NotifyIcon _notifyIcon;

        public static Timer SyncTimer { get; private set; }

        protected override void OnStartup(StartupEventArgs e) {
            base.OnStartup(e);
            
            if (Settings.Default.SyncSources == null)
                Settings.Default.SyncSources = new List<Source>();

            if (Settings.Default.IsFirstRun)
                OnFirstRun();
            Settings.Default.IsFirstRun = false;

            SyncProcess.Instance.SourceSynced += Instance_SourceSynced;
            SyncProcess.Instance.SourceSynced += Source.ReleaseCache;

            UpdatesChecker.NewVersionIsAvailable += UpdatesChecker_NewVersionIsAvailable;
            UpdatesChecker.StartNewVersionChecking();

            ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown;
            var ctxMenu = new ContextMenuStrip();

            ctxMenu.Items.Add("Settings", Res.IconSettings, ShowSettings);
            ctxMenu.Items.Add("Sync Now", Res.ActionRefreshBlue, SyncNow);
            ctxMenu.Items.Add("-");
            ctxMenu.Items.Add("Pause All", Res.ControlPause, delegate { PauseAll(); });
            ctxMenu.Items.Add("Resume All", Res.ControlPlay, delegate { ResumeAll(); });
            ctxMenu.Items.Add("-");
            ctxMenu.Items.Add("About", Res.IconInfo, ShowAbout);
            ctxMenu.Items.Add("-");
            ctxMenu.Items.Add("Exit", Res.Cancel, delegate { Shutdown(); });

            _notifyIcon = new NotifyIcon {
                                             Icon = Res.AppIcon,
                                             ContextMenuStrip = ctxMenu,
                                             Visible = true
                                         };
            _notifyIcon.MouseDoubleClick += _notifyIcon_MouseDoubleClick;
            
            SyncTimer = new Timer();
            SyncTimer.Tick += _timer_Tick;
            int ticks = (int)TimeSpan.FromMinutes(Settings.Default.SyncIntervalInMinutes).TotalMilliseconds;
            if (ticks > 0)
            {
                SyncTimer.Interval = ticks;
                SyncTimer.Start();
            }           
        }

        private static void OnFirstRun() {
            AddToStartup();
        }

        void Instance_SourceSynced(object sender, AnjLab.FX.Sys.EventArgs<Source, string> e)
        {
            if (!Settings.Default.NotifyAboutSyncResults)
                return;

            var handler = new EventHandler(delegate {
                                               _notifyIcon.ShowBalloonTip(3000, "AnjLab.SycIT - " + e.Item1.Title, e.Item2, ToolTipIcon.Info);
                                           });
            Dispatcher.Invoke(DispatcherPriority.Render, handler, this, EventArgs.Empty);
        }

        void UpdatesChecker_NewVersionIsAvailable(object sender, EventArgs e)
        {
            var handler = new EventHandler(delegate {
                                               var wnd = new NewVersionWindow();
                                               wnd.ShowDialog();
                                           });
            Dispatcher.Invoke(DispatcherPriority.Send, handler, this, EventArgs.Empty);
        }

        void _notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ShowSettings(sender, e);
        }

        static void _timer_Tick(object sender, EventArgs e)
        {
            SyncProcess.Instance.Start(Settings.Default.SyncSources);
        }

        protected override void OnExit(ExitEventArgs e) {
            base.OnExit(e);
            Settings.Default.Save();
            if (_notifyIcon != null)
                _notifyIcon.Dispose();
        }

        private MainWindow _settings;

        public void ShowSettings(object  sender, EventArgs e) {
            if (_settings != null) {
                _settings.WindowState = WindowState.Normal;
                _settings.Activate();
                return;
            }
            _settings = new MainWindow();
            _settings.ShowDialog();
            _settings = null;
        }

        public void ShowAbout(object sender, EventArgs e)
        {
            AboutWindow.ShowSingle();
        }

        public void SyncNow(object sender, EventArgs e) {
            SyncProcess.Instance.Start(Settings.Default.SyncSources);
        }

        public static void PauseAll() {
            foreach (var source in Settings.Default.SyncSources)
            {
                source.Paused = true;
            }
        }
        public static void ResumeAll() {
            foreach (var source in Settings.Default.SyncSources)
            {
                source.Paused = false;
            }
        }

        public static void StartBrowser(string url)
        {
            var process = new Process { StartInfo = { FileName = url } };
            process.Start();
        }

        private const string LnkFileName = @"\anjlab.syncit.lnk";

        public static void AddToStartup()
        {
            RemoveFromStartup();
            var path = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
            var shell = new WshShellClass();
            var shortcut = (IWshShortcut)shell.CreateShortcut(path + LnkFileName);
            shortcut.TargetPath = GetAppPath();
            shortcut.WorkingDirectory = Environment.CurrentDirectory;
            shortcut.Description = "AnjLab.SyncIT";
            shortcut.Save();
        }

        public static void RemoveFromStartup()
        {
            var path = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
            if (System.IO.File.Exists(path + LnkFileName))
                System.IO.File.Delete(path + LnkFileName);
        }

        public static string GetAppPath()
        {
            var path = Assembly.GetExecutingAssembly().Location;
            return "\"" + path + "\"";
        }

        public static bool IsAddedToAutostart()
        {
            var path = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
            return System.IO.File.Exists(path + LnkFileName);
        }
    }
}